
# edge_tts_tts.py
import asyncio
from pathlib import Path
import uuid
import edge_tts
from .tts_base import BaseTTS
from .tts_registry import register_tts
from config import app_config

@register_tts("edge_tts")
class EdgeTTSTTS(BaseTTS):
    def __init__(self, voice: str = "zh-CN-XiaoxiaoNeural", rate: str = "+0%", volume: str = "+0%") -> None:
        """
        初始化 Edge TTS 服务
        :param voice: 语音角色，如 'en-US-JennyNeural', 'zh-CN-XiaoxiaoNeural' 等
        :param rate: 语速，如 '+10%', '-5%'
        :param volume: 音量，如 '+5dB', '-3dB'，但 edge-tts 使用百分比字符串如 "+0%"
        """
        self.voice = voice
        self.rate = rate
        self.volume = volume  # 注意：edge-tts 目前对 volume 支持有限，部分通过后处理调整

    def synthesize(self, text: str, **kwargs) -> str:
        # 支持运行时参数覆盖
        voice = kwargs.get("voice", self.voice)
        rate = kwargs.get("rate", self.rate)
        volume = kwargs.get("volume", self.volume)

        output_dir = app_config.TTS_FILE_OUT_PATH
        output_filename = f"tts_output_{uuid.uuid4().hex[:8]}.mp3"
        output_path = Path(output_dir) / output_filename
        
        asyncio.run(self._synthesize_async(text, output_path, voice, rate, volume))
        return str(output_path)

    async def _synthesize_async(self, text: str, output_file: Path, voice: str, rate: str, volume: str):
        """
        异步核心：调用 edge-tts 生成语音
        """
        communicate = edge_tts.Communicate(text, voice=voice, rate=rate, volume=volume)
        await communicate.save(str(output_file))
    
    def cleanup(self):
        """Edge TTS 无需显式释放资源"""
        pass

# --------------------------
# 使用示例
# --------------------------
if __name__ == "__main__":
    pass